/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.myhelper;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author DOWN
 */
@FacesValidator("jsonValidator")
public class JsonValidator implements Validator {


    
    public boolean isJSONValid(String test)
    {
        try {
            new JSONObject(test);
            return true;
        } catch(JSONException ex) { 
            return false;
        }
    }

    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException {
        if (isJSONValid(o.toString())) {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Email is not valid.");
            message.setDetail("Email is not valid.");
            fc.addMessage("userForm:Email", message);
            throw new ValidatorException(message);
        }
    }
}
